package com.ruyuan.eshop.construction.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruyuan.eshop.common.exception.CommonErrorCodeEnum;
import com.ruyuan.eshop.common.exception.ProductBizException;
import com.ruyuan.eshop.construction.converter.FrontCategoryConverter;
import com.ruyuan.eshop.construction.domain.entity.FrontCategoryDO;
import com.ruyuan.eshop.construction.domain.entity.FrontCategoryTreeDO;
import com.ruyuan.eshop.construction.domain.request.FrontCategoryRequest;
import com.ruyuan.eshop.construction.domain.request.QueryCategoryRequest;
import com.ruyuan.eshop.construction.mapper.FrontCategoryMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 *  商品审核 资源管理
 * @author : zhonghuashishan
 *
 */
@Repository
public class FrontCategoryRepository {

    @Resource
    private FrontCategoryConverter frontCategoryConverter;

    @Resource
    private FrontCategoryMapper frontCategoryMapper;

    /**
     * 查询前台类目树
     * @param queryCategoryRequest
     * @return
     */
    public List<FrontCategoryTreeDO> selectTree(QueryCategoryRequest queryCategoryRequest){
        return frontCategoryMapper.selectTree(queryCategoryRequest);
    }
    /**
     * 查询某个层级的前端类目树
     * @param categoryQueryRequest
     * @return
     */
    public List<FrontCategoryDO> listBy(QueryCategoryRequest categoryQueryRequest){
        FrontCategoryDO frontCategoryDO = frontCategoryConverter.converterDO(categoryQueryRequest);

        LambdaQueryWrapper<FrontCategoryDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.orderByAsc(FrontCategoryDO::getCategorySort);
        queryWrapper.setEntity(frontCategoryDO);

        return frontCategoryMapper.selectList(queryWrapper);
    }

    /**
     * 新增或者修改前端类目树
     * @param frontCategoryRequest
     */
    public void saveOrUpdate(FrontCategoryRequest frontCategoryRequest){
        if (Objects.isNull(frontCategoryRequest.getId())) {
            save(frontCategoryRequest);
        } else {
            update(frontCategoryRequest);
        }
    }

    private void save(FrontCategoryRequest frontCategoryRequest) {
        FrontCategoryDO frontCategoryDO = frontCategoryConverter.converterDO(frontCategoryRequest);
        frontCategoryDO.initCommon();

        int count = frontCategoryMapper.insert(frontCategoryDO);

        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }


    private void update(FrontCategoryRequest frontCategoryRequest) {
        frontCategoryMapper.updateById(frontCategoryConverter.converterDO(frontCategoryRequest));
    }


}
